module.exports = (sequelize, DataTypes) => {
  const HealthRecord = sequelize.define('HealthRecord', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    member_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '关联家庭成员ID'
    },
    type: {
      type: DataTypes.STRING,
      allowNull: false,
      comment: '记录类型，如：血压、血糖、体重等'
    },
    type_id: {
      type: DataTypes.STRING,
      allowNull: true,
      comment: '记录类型ID，如：bloodPressure、bloodSugar、weight等'
    },
    value: {
      type: DataTypes.STRING,
      allowNull: false,
      comment: '记录值，如：120/80 mmHg、5.6 mmol/L、65 kg等'
    },
    raw_value: {
      type: DataTypes.FLOAT,
      allowNull: true,
      comment: '原始数值，用于统计分析'
    },
    raw_value2: {
      type: DataTypes.FLOAT,
      allowNull: true,
      comment: '第二个原始数值，用于如血压等有两个值的记录'
    },
    unit: {
      type: DataTypes.STRING,
      allowNull: true,
      comment: '单位，如：mmHg、mmol/L、kg等'
    },
    record_time: {
      type: DataTypes.DATE,
      allowNull: false,
      comment: '记录时间'
    },
    note: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '备注'
    },
    status: {
      type: DataTypes.ENUM('normal', 'warning', 'abnormal'),
      defaultValue: 'normal',
      comment: '记录状态，正常、警告、异常'
    }
  }, {
    tableName: 'health_records',
    timestamps: true,
    paranoid: true,
    hooks: {
      beforeCreate: (record) => {
        // 解析原始值，用于统计分析
        if (record.value && !record.raw_value) {
          // 血压特殊处理
          if (record.type === '血压' || record.type_id === 'bloodPressure') {
            const match = record.value.match(/(\d+)\/(\d+)/);
            if (match) {
              record.raw_value = parseFloat(match[1]);
              record.raw_value2 = parseFloat(match[2]);
            }
          } else {
            // 其他类型记录
            const match = record.value.match(/(\d+\.?\d*)/);
            if (match) {
              record.raw_value = parseFloat(match[1]);
            }
          }
        }
        
        // 自动评估记录状态
        if (record.type_id === 'bloodPressure' && record.raw_value && record.raw_value2) {
          if (record.raw_value >= 140 || record.raw_value2 >= 90) {
            record.status = 'warning';
          }
          if (record.raw_value >= 160 || record.raw_value2 >= 100) {
            record.status = 'abnormal';
          }
        } else if (record.type_id === 'bloodSugar' && record.raw_value) {
          if (record.raw_value >= 7.0 || record.raw_value <= 3.9) {
            record.status = 'warning';
          }
          if (record.raw_value >= 11.1 || record.raw_value <= 3.0) {
            record.status = 'abnormal';
          }
        }
      }
    }
  });

  HealthRecord.associate = function(models) {
    HealthRecord.belongsTo(models.FamilyMember, {
      foreignKey: 'member_id',
      as: 'member'
    });
  };

  return HealthRecord;
}; 